package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.IShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <b><code>ShoppingCartController</code></b>
 * <p/>
 * Description
 * <p/>
 * <b>Creation Time:</b> 29/06/2024 18:36.
 *
 * @author yanjr
 * @since reggie_take_out
 */
@RequestMapping("/shoppingCart")
@RestController
public class ShoppingCartController {

    @Autowired
    private IShoppingCartService shoppingCartService;

    /**
     * 查询购物车
     * @return 购物车信息
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(HttpServletRequest request) {
        return R.success(shoppingCartService.list(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, request.getSession().getAttribute("employee"))));
    }

    /**
     * 添加购物车
     * @param shoppingCart 购物车信息
     * @return 购物车信息
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        Long userId = BaseContext.getCurrentUser();
        shoppingCart.setUserId(userId);
        ShoppingCart res = shoppingCartService.add(shoppingCart);
        return R.success(res);
    }

    /**
     * 购物车数量减1
     * @param shoppingCart 购物车信息
     * @return 是否成功
     */
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        return shoppingCartService.sub(shoppingCart);
    }

    /**
     * 清空购物车
     * @return 是否成功
     */
    @DeleteMapping("/clean")
    public R<String> clean() {
        shoppingCartService.remove(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, BaseContext.getCurrentUser()));
        return R.success("清空成功");
    }

}
